package com.android.versiondownloadlibrary;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import java.io.File;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by $Liudan on 2018/6/1 0001.
 */

public class VersionMgr {
    public static VersionMgr getInstance() {
        return VersionMgrHolder.versionMgr;
    }

    private static class VersionMgrHolder {
        public static final VersionMgr versionMgr = new VersionMgr();
    }

    public void httpRequest(final Context context, String url, int update_mode, final Handler mhandler, final UpdateUi updateUi) {

        File mFile = RangeWriteFileUtil.getFutureStudioIconFile();
        long length = 0;
        if (mFile != null) {
            length = mFile.length();
        }

        Log.d(this.getClass().getName(), "请求下载的初始位置：" + length);
        //定制OkHttp
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient
                .Builder();
        if (BuildConfig.DEBUG) {//发布版本不再打印
            // 日志显示级别
            HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BASIC;
            //新建log拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d(this.getClass().getName(), "okhttp--11111111111message===" + message);
                }
            });
            loggingInterceptor.setLevel(level);
            //OkHttp进行添加拦截器loggingInterceptor
            httpClientBuilder.addInterceptor(loggingInterceptor);
        }
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.rhb-tech.com/") // 设置 网络请求 base Url
                .client(httpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                .build();
        // 步骤5:创建 网络请求接口 的实例
        ApiInterface request = retrofit.create(ApiInterface.class);
        //对 发送请求 进行封装
        Call<ResponseBody> call = request.download("bytes=" + length + "-", url);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d(this.getClass().getName(), "下载" + response.body());
//                writeFile(response.body());
                RangeWriteFileUtil.writeFile(response.body(),mhandler,updateUi);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }

        });
    }
}
